package Part1_java.util.Collection.List.ArrayList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * ClassName: ArrayListTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.01 23:32
 */
public class ArrayListTest {
    public static void main(String[] args) {
        //1、随机生成30个字符，放入ArrayList中
        ArrayList<Object> list = new ArrayList<>();

        for(int i = 0; i<30; i++){
            list.add((char)(Math.random() * (122-97+1)+97) + "");
        }

        System.out.println(list);

        System.out.println(listOp(list, "a"));
        System.out.println(listOp(list, "b"));
        System.out.println(listOp(list, "c"));
        System.out.println("*****************************************");

        System.out.println(findAnagrams("cbaebabacd","abc"));

    }

    //遍历list，找出指定元素次数
    public static int listOp(Collection list, String s){
        int count = 0;
        for(Object object : list){
            if(s.equals(object))
                count++;
        }
        return count;
    }

    public static List<Integer> findAnagrams(String s, String p) {

        /*List<Integer> ans = new ArrayList<>();
        int leng = p.toCharArray().length;

        char[] arr = s.toCharArray();

        int left = 0;
        int right = left + leng - 1;

        while(right<arr.length){
            char[] chars = new char[leng];
            for(int i=0; i<leng; i++){
                chars[i] = arr[left+i];
            }
            Arrays.sort(chars);
            if(p.equals(String.valueOf(chars))){
                ans.add(left);
                left++;
                right++;
            }else{
                left++;
                right++;
            }
        }
        return ans;*/
        List<Integer> ans = new ArrayList<>();
        if(s.length() < p.length()) return ans;

        int[] counts = new int[26];
        for(int i=0; i<p.length(); i++){
            counts[p.charAt(i) - 'a']++;
        }

        int[] curCounts = new int[26];
        for(int i=0; i<p.length()-1; i++){
            curCounts[s.charAt(i) - 'a']++;
        }

        for(int left=0, right=p.length()-1; right<s.length(); right++,left++){
            curCounts[s.charAt(right) - 'a']++;
            if(Arrays.equals(counts, curCounts)){
                ans.add(left);
            }
            curCounts[s.charAt(left) - 'a']--;
        }

        return ans;
    }
}
